package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.entity.vo.OperationLogVO;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.RunningReportAuditConfigMapper;
import com.mingqijia.gassafety.db.mapper.RunningReportConfigMapper;
import com.mingqijia.gassafety.db.mapper.WarningRecordMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.constant.runningReport.ReportNoAuditAlarmStatusEnum;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.webserver.request.RunningReportConfigRequest;
import com.mingqijia.gassafety.webserver.request.RunningReportTemplateRequest;
import com.mingqijia.gassafety.webserver.request.RunningStrategyExtRequest;
import com.mingqijia.gassafety.webserver.request.runningReport.RunningReportAuditConfigListRequest;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.response.RunningReportConfigResponse;
import com.mingqijia.gassafety.webserver.response.RunningReportTemplateResponse;
import com.mingqijia.gassafety.webserver.response.runningReport.RunningReportAuditConfigListResponse;
import com.mingqijia.gassafety.webserver.service.RunningReportConfigService;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 运行报告配置 服务实现类
 * </p>
 *
 * @author mby
 * @since 2024-03-11
 */
@Service
@Slf4j
public class RunningReportConfigServiceImpl extends ServiceImpl<RunningReportConfigMapper, RunningReportConfig> implements RunningReportConfigService {

    @Autowired
    ConsumerMapper consumerMapper;

    @Autowired
    RunningReportAuditConfigMapper runningReportAuditConfigMapper;

    @Override
    public RunningReportConfigResponse configDetail() {
        String spId = ApplicationUtils.getWorkingSpId();

        RunningReportConfigResponse runningReportConfigResponse = new RunningReportConfigResponse();
        //判断运行报告配置信息是否存在
        QueryWrapper<RunningReportConfig> runningReportConfigWrapper = new QueryWrapper<>();
        runningReportConfigWrapper.lambda().eq(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportConfig::getSpId, spId);
        RunningReportConfig runningReportConfig = this.getOne(runningReportConfigWrapper);
        if (runningReportConfig == null || (runningReportConfig != null && runningReportConfig.getConfigUpdatedAt() == null)) {
            // 未配置过，用默认配置
            runningReportConfigResponse.setGenerateReportOpen(OpenCloseEnum.CLOSE.getCode());
            runningReportConfigResponse.setGenerateReportDay(2);
            runningReportConfigResponse.setNoAuditList(new ArrayList<>()); // 无需审核配置为空
            runningReportConfigResponse.setIsOfflineConfig(1); // 默认不开启
            runningReportConfigResponse.setOfflineInclude(0); // 默认不计入统计

        } else {
            BeanUtil.copyProperties(runningReportConfig, runningReportConfigResponse);
            // 查询无需审核配置列表
            QueryWrapper<RunningReportAuditConfig> runningReportAuditConfigWrapper = new QueryWrapper<>();
            runningReportAuditConfigWrapper.lambda().eq(RunningReportAuditConfig::getConfigId, runningReportConfig.getId())
                .eq(RunningReportAuditConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportAuditConfig::getSpId, spId);
            runningReportConfigResponse.setNoAuditList(runningReportAuditConfigMapper.selectList(runningReportAuditConfigWrapper).stream().map(x -> {
                RunningReportAuditConfigListResponse vo = new RunningReportAuditConfigListResponse();
                BeanUtils.copyProperties(x, vo);
                return vo;
            }).collect(Collectors.toList()));
        }

        return runningReportConfigResponse;
    }

    @Override
    public RunningReportTemplateResponse templateDetail(Boolean isDefault) {
        String spId = ApplicationUtils.getWorkingSpId();

        RunningReportTemplateResponse runningReportTemplateResponse = new RunningReportTemplateResponse();
        //判断该客户是否存在
        QueryWrapper<RunningReportConfig> runningReportConfigWrapper = new QueryWrapper<>();
        runningReportConfigWrapper.lambda().eq(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportConfig::getSpId, spId);
        RunningReportConfig runningReportConfig = this.getOne(runningReportConfigWrapper);
        if (runningReportConfig == null || isDefault || (runningReportConfig != null && runningReportConfig.getTemplateUpdatedAt() == null)) {
            // 未配置过，用默认配置
            runningReportTemplateResponse.setHeaderShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setHeaderLogo(Constants.RUNNING_REPORT_HEADER_LOGO);
            runningReportTemplateResponse.setHeaderContent("报警监控中心");
            runningReportTemplateResponse.setNoAlarmContent(Constants.RUNNING_REPORT_NO_ALARM_CONTENT);
            runningReportTemplateResponse.setNoAlarmTipsShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setIsAlarmSummary(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setAlarmSummaryContent(Constants.RUNNING_REPORT_ALARM_SUMMARY_CONTENT);
            runningReportTemplateResponse.setAlarmSummaryTitle(Constants.RUNNING_REPORT_ALARM_SUMMARY_TITLE);
            List<FieldListShowResponse> alarmSummaryList = new ArrayList<>();
            runningReportTemplateResponse.setAlarmSummaryList(alarmSummaryList);
            alarmSummaryList.add(new FieldListShowResponse("time", "事件时间", 1, 0, 1));
            alarmSummaryList.add(new FieldListShowResponse("alarmType", "事件", 2, 0, 1));
            alarmSummaryList.add(new FieldListShowResponse("valveBrokenInfo", "事件原因", 3, 0, 0));
            alarmSummaryList.add(new FieldListShowResponse("alarmNumber", "次数", 4, 0, 1));
            alarmSummaryList.add(new FieldListShowResponse("proportion", "当月占比", 5, 0, 0));
            alarmSummaryList.add(new FieldListShowResponse("appealStatus", "处理状态", 6, 0, 0));
            runningReportTemplateResponse.setCategoryAnalysisShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setSituationAnalysisShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setIsAlarmDetail(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setAlarmDetailTitle(Constants.RUNNING_REPORT_ALARM_DETAIL_TITLE);
            runningReportTemplateResponse.setAlarmDetailNameShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setAlarmDetailCodeShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setAlarmDetailAddressShow(ShowAndSelectEnum.SHOW.getCode());
            List<FieldListShowResponse> alarmDetailist = new ArrayList<>();
            runningReportTemplateResponse.setAlarmDetailList(alarmDetailist);
            alarmDetailist.add(new FieldListShowResponse("number", "序号", 1, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("imei", "设备号", 2, 0, 1));
            alarmDetailist.add(new FieldListShowResponse("alarmAddress", "地点", 3, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("alarmType", "事件", 4, 0, 1));
            alarmDetailist.add(new FieldListShowResponse("alarmTime", "事件时间", 5, 0, 1));
            alarmDetailist.add(new FieldListShowResponse("concentration", "事件记录", 6, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("appealTime", "处理时间", 7, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("appealStatus", "处理状态", 8, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("valveBrokenInfo", "事件原因", 9, 0, 0));
            runningReportTemplateResponse.setIsTips(ShowAndSelectEnum.SHOW.getCode());
            runningReportTemplateResponse.setTipsContent(Constants.RUNNING_REPORT_TIPS_CONTENT);
            runningReportTemplateResponse.setTipsShow(ShowAndSelectEnum.SHOW.getCode());
        } else {
            BeanUtil.copyProperties(runningReportConfig, runningReportTemplateResponse);
            if (StringUtils.isNotEmpty(runningReportConfig.getAlarmSummaryListShow())) {
                runningReportTemplateResponse.setAlarmSummaryList(JSON.parseArray(runningReportConfig.getAlarmSummaryListShow(), FieldListShowResponse.class));
            }
            if (StringUtils.isNotEmpty(runningReportConfig.getAlarmDetailListShow())) {
                runningReportTemplateResponse.setAlarmDetailList(JSON.parseArray(runningReportConfig.getAlarmDetailListShow(), FieldListShowResponse.class));
            }
        }
        return runningReportTemplateResponse;
    }

    @Override
    @Transactional
    public void editConfig(RunningReportConfigRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        RunningReportConfigResponse response = configDetail();
        log.info("runningReportConfigResponse:{}", response);
        // 查询运行报告配置信息是否存在
        QueryWrapper<RunningReportConfig> runningReportConfigWrapper = new QueryWrapper<>();
        runningReportConfigWrapper.lambda().eq(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportConfig::getSpId, spId);
        RunningReportConfig runningReportConfig = this.getOne(runningReportConfigWrapper);
        Integer oldId = null;
        if (runningReportConfig == null) {
            runningReportConfig = new RunningReportConfig();
            //设置默认的运行报告模版
            runningReportConfig.setHeaderShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setHeaderLogo(Constants.RUNNING_REPORT_HEADER_LOGO);
            runningReportConfig.setHeaderContent("报警监控中心");
            runningReportConfig.setNoAlarmContent(Constants.RUNNING_REPORT_NO_ALARM_CONTENT);
            runningReportConfig.setNoAlarmTipsShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setIsAlarmSummary(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setAlarmSummaryContent(Constants.RUNNING_REPORT_ALARM_SUMMARY_CONTENT);
            runningReportConfig.setAlarmSummaryTitle(Constants.RUNNING_REPORT_ALARM_SUMMARY_TITLE);
            List<FieldListShowResponse> alarmSummaryList = new ArrayList<>();
            alarmSummaryList.add(new FieldListShowResponse("time", "事件事件", 1, 0, 1));
            alarmSummaryList.add(new FieldListShowResponse("alarmType", "事件", 2, 0, 1));
            alarmSummaryList.add(new FieldListShowResponse("valveBrokenInfo", "事件原因", 3, 0, 0));
            alarmSummaryList.add(new FieldListShowResponse("alarmNumber", "次数", 4, 0, 1));
            alarmSummaryList.add(new FieldListShowResponse("proportion", "当月占比", 5, 0, 0));
            alarmSummaryList.add(new FieldListShowResponse("appealStatus", "处理状态", 6, 0, 0));
            runningReportConfig.setAlarmSummaryListShow(JSON.toJSONString(alarmSummaryList));
            runningReportConfig.setCategoryAnalysisShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setSituationAnalysisShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setIsAlarmDetail(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setAlarmDetailTitle(Constants.RUNNING_REPORT_ALARM_DETAIL_TITLE);
            runningReportConfig.setAlarmDetailNameShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setAlarmDetailCodeShow(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setAlarmDetailAddressShow(ShowAndSelectEnum.SHOW.getCode());
            List<FieldListShowResponse> alarmDetailist = new ArrayList<>();
            alarmDetailist.add(new FieldListShowResponse("number", "序号", 1, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("imei", "设备号", 2, 0, 1));
            alarmDetailist.add(new FieldListShowResponse("alarmAddress", "地点", 3, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("alarmType", "事件", 4, 0, 1));
            alarmDetailist.add(new FieldListShowResponse("alarmTime", "事件时间", 5, 0, 1));
            alarmDetailist.add(new FieldListShowResponse("concentration", "事件记录", 6, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("appealTime", "处理时间", 7, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("appealStatus", "处理状态", 8, 0, 0));
            alarmDetailist.add(new FieldListShowResponse("valveBrokenInfo", "事件原因", 9, 0, 0));
            runningReportConfig.setAlarmDetailListShow(JSON.toJSONString(alarmDetailist));
            runningReportConfig.setIsTips(ShowAndSelectEnum.SHOW.getCode());
            runningReportConfig.setTipsContent(Constants.RUNNING_REPORT_TIPS_CONTENT);
            runningReportConfig.setTipsShow(ShowAndSelectEnum.SHOW.getCode());
        } else {
            oldId = runningReportConfig.getId();
            // 如果前端是关闭的，数据库也是关闭 则除开启状态外不能更改其他项
            if (OpenCloseEnum.CLOSE.getCode().equals(request.getGenerateReportOpen()) && OpenCloseEnum.CLOSE.getCode().equals(runningReportConfig.getGenerateReportOpen())) throw new BizException("设备运行报告生成开关未开启，禁止修改其他配置项");
        }
        // 校验无需审核配置
        if (checkNoAuditConfig(request.getNoAuditList())) {
            throw new BizException("无需审核配置重复");
        }

        // 删除之前的
        UpdateWrapper<RunningReportConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportConfig::getSpId, spId)
                .set(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_TRUE);
        this.update(updateWrapper);
        BeanUtils.copyProperties(request, runningReportConfig);
        runningReportConfig.setCheckOpen(request.getCheckOpenShow() == null ? Constants.BLANK : JSON.toJSONString(request.getCheckOpenShow()));
        runningReportConfig.setConfigUpdatedAt(new Date());
        runningReportConfig.setSpId(spId);
        this.save(runningReportConfig);
        // 保存明细
        if (CollectionUtils.isNotEmpty(request.getNoAuditList())) {
            for (RunningReportAuditConfigListRequest auditConfig : request.getNoAuditList()) {
                RunningReportAuditConfig runningReportAuditConfig = new RunningReportAuditConfig();
                runningReportAuditConfig.setConfigId(runningReportConfig.getId());
                runningReportAuditConfig.setCustType(auditConfig.getCustType());
                runningReportAuditConfig.setAlarmStatus(auditConfig.getAlarmStatus());
                runningReportAuditConfig.setSpId(spId);
                runningReportAuditConfigMapper.insert(runningReportAuditConfig);
            }
        }
        //企业级操作日志
        LogVO vo = new LogVO();
        log.info("editConfig-response:{}", JSONObject.toJSONString(response));
        log.info("editConfig-runningReportConfig:{}", JSONObject.toJSONString(runningReportConfig));
        StringBuilder stringBuilder = new StringBuilder();
        if (!response.getGenerateReportOpen().equals(runningReportConfig.getGenerateReportOpen())) {
            stringBuilder.append("设备运行报告生成开关：由【").append(OpenCloseEnum.getOpenClose(response.getGenerateReportOpen()).getName()).append("】变更成【").append(OpenCloseEnum.getOpenClose(runningReportConfig.getGenerateReportOpen()).getName()).append("】\n");
        }
        if (response.getGenerateReportDay() != runningReportConfig.getGenerateReportDay()) {
            stringBuilder.append("设备运行报告生成时间设置：由每月的【").append(response.getGenerateReportDay()).append("】日变更成【").append(runningReportConfig.getGenerateReportDay()).append("】日\n");
        }
        StringBuilder checkDetail = new StringBuilder();
        // 查询原来的
        List<RunningReportAuditConfig> runningReportAuditConfigList = new ArrayList<>();
        Map<Integer, RunningReportAuditConfig> runningReportAuditConfigMap = new HashMap<>();
        if (oldId != null) {
            QueryWrapper<RunningReportAuditConfig> runningReportAuditConfigWrapper = new QueryWrapper<>();
            runningReportAuditConfigWrapper.lambda().eq(RunningReportAuditConfig::getConfigId, oldId)
                .eq(RunningReportAuditConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportAuditConfig::getSpId, spId);
            runningReportAuditConfigList = runningReportAuditConfigMapper.selectList(runningReportAuditConfigWrapper);
            if (CollectionUtils.isNotEmpty(runningReportAuditConfigList)) {
                runningReportAuditConfigList.forEach(x -> {
                    runningReportAuditConfigMap.put(x.getId(), x);
                });
            }
        }
        log.info("editConfig-runningReportAuditConfigMap:{},{}", JSONObject.toJSONString(runningReportAuditConfigMap), oldId);
        List<Integer> editIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(request.getNoAuditList())) {
            for (RunningReportAuditConfigListRequest noAudit : request.getNoAuditList()) {
                if (noAudit.getId() == null) {
                    // 新增
                    checkDetail.append("\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000新增用户类型【").append(StringUtils.isBlank(noAudit.getCustType()) ? "全部" : noAudit.getCustType()).append("】，报警记录状态【")
                        .append(ReportNoAuditAlarmStatusEnum.getNameByCode(noAudit.getAlarmStatus())).append("】\n");
                } else {
                    // 编辑
                    editIds.add(noAudit.getId());
                    if (runningReportAuditConfigMap.get(noAudit.getId()) != null) {
                        RunningReportAuditConfig oldAuditConfig = runningReportAuditConfigMap.get(noAudit.getId());
                        if (!oldAuditConfig.getCustType().equals(noAudit.getCustType()) || !oldAuditConfig.getAlarmStatus().equals(noAudit.getAlarmStatus())) {
                            checkDetail.append("\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000编辑");
                            if (!oldAuditConfig.getCustType().equals(noAudit.getCustType())) {
                                checkDetail.append("用户类型由【").append(StringUtils.isBlank(oldAuditConfig.getCustType()) ? "全部" : oldAuditConfig.getCustType())
                                    .append("】变更成【").append(StringUtils.isBlank(noAudit.getCustType()) ? "全部" : noAudit.getCustType())
                                    .append("】，");
                            }
                            if (!oldAuditConfig.getAlarmStatus().equals(noAudit.getAlarmStatus())) {
                                checkDetail.append("报警记录状态由【").append(ReportNoAuditAlarmStatusEnum.getNameByCode(oldAuditConfig.getAlarmStatus()))
                                    .append("】变更成【").append(ReportNoAuditAlarmStatusEnum.getNameByCode(oldAuditConfig.getAlarmStatus())).append("】，");
                            }
                            checkDetail.deleteCharAt(checkDetail.length() - 1).append("\n");
                        }
                    }
                }
            }
        }
        // 删除
        log.info("editConfig-editIds:{},{}", editIds, runningReportAuditConfigList);
        if (CollectionUtils.isNotEmpty(runningReportAuditConfigList)) {
            for (RunningReportAuditConfig runningReportAuditConfig : runningReportAuditConfigList) {
                if (!editIds.contains(runningReportAuditConfig.getId())) {
                    checkDetail.append("\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000删除用户类型【").append(StringUtils.isBlank(runningReportAuditConfig.getCustType()) ? "全部" : runningReportAuditConfig.getCustType()).append("】，报警记录状态【")
                        .append(ReportNoAuditAlarmStatusEnum.getNameByCode(runningReportAuditConfig.getAlarmStatus())).append("】\n");
                }
            }
        }

        if (checkDetail.length() > 0) {
            stringBuilder.append("设备运行报告无需审核配置：").append(checkDetail.substring(13, checkDetail.length()).toString());
        }

        // 配置类型离线事件
        StringBuilder offlineDetail = new StringBuilder();
        if (!response.getIsOfflineConfig().equals(runningReportConfig.getIsOfflineConfig())) {
            if (runningReportConfig.getIsOfflineConfig() == 0) {
                offlineDetail.append("启用【离线事件】成功，");
            } else {
                offlineDetail.append("禁用【离线事件】成功，");
            }
        }
        // 离线间隔时间
        log.info("editConfig-offlineInterval:{},{}", response.getOfflineInterval(), runningReportConfig.getOfflineInterval());
        if ((response.getOfflineInterval() == null && runningReportConfig.getOfflineInterval() != null)
            || (response.getOfflineInterval() != null && runningReportConfig.getOfflineInterval() == null)
            || (response.getOfflineInterval() != null && runningReportConfig.getOfflineInterval() != null && !response.getOfflineInterval().equals(runningReportConfig.getOfflineInterval()))) {
            offlineDetail.append("规则1由【").append(response.getOfflineInterval() == null ? Constants.BLANK : response.getOfflineInterval())
                .append("】小时变更成【").append(runningReportConfig.getOfflineInterval() == null ? Constants.BLANK : runningReportConfig.getOfflineInterval()).append("】小时，");
        }
        // 是否计入统计
        if (!response.getOfflineInclude().equals(runningReportConfig.getOfflineInclude())) {
            offlineDetail.append("规则2由【").append(response.getOfflineInclude() == 0 ? "不计入统计" : "计入统计")
                .append("】变更成【").append(runningReportConfig.getOfflineInclude() == 0 ? "不计入统计" : "计入统计").append("】，");
        }
        if (offlineDetail.length() > 0) {
            stringBuilder.append("配置类型：").append(offlineDetail.deleteCharAt(offlineDetail.length() - 1));
        }

        vo.setDetail(stringBuilder.toString());
        log.info("LogVO-vo:{}", JSONObject.toJSONString(vo));
        LogRecordAspect.threadLocal.set(vo);

    }

    /**
     * 校验无需审核配置是不是有重复配置的地方  true-有重复  false-无重复
     * @param auditConfigList
     * @return
     */
    public boolean checkNoAuditConfig(List<RunningReportAuditConfigListRequest> auditConfigList) {
        if (CollectionUtils.isEmpty(auditConfigList)) {
            return false;
        }
        List<String> noAuditConfigList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(auditConfigList)) {
            for (RunningReportAuditConfigListRequest runningReportAuditConfig : auditConfigList) {
                List<String> custTypeList = getCustTypeList(runningReportAuditConfig.getCustType());
                List<Integer> alarmStatusList = getAlarmStatus(runningReportAuditConfig.getAlarmStatus());
                for (String custType : custTypeList) {
                    for (Integer alarmStatus : alarmStatusList) {
                        String sign = new StringBuffer(Constants.BLANK).append(custType).append(Constants.STR_STRIKETHROUGH).append(alarmStatus).toString();
                        if (noAuditConfigList.contains(sign)) {
                            return true;
                        }
                        noAuditConfigList.add(sign);
                    }
                }

            }
        }
        return false;
    }

    /**
     * 根据spId获取用户类型列表
     * @param custType
     * @return
     */
    public List<String> getCustTypeList(String custType) {
        if (StringUtils.isNotBlank(custType)) {
            return Arrays.asList(custType);
        }

        String spId = ApplicationUtils.getWorkingSpId();
        List<String> custTypes = consumerMapper.selectUserType(spId);
        if (CollectionUtils.isNotEmpty(custTypes)) {
            custTypes.remove("");
            // 其他
            if (consumerMapper.selectUserTypeCount(spId, "其他") > 0) {
                custTypes.add("其他");
            }
            // 未知
            if (consumerMapper.selectUserTypeCount(spId, "未知") > 0) {
                custTypes.add("未知");
            }
        }

        return custTypes;
    }

    /**
     * 根据spId获取用户类型列表
     * @return
     */
    public List<Integer> getAlarmStatus(Integer alarmStatus) {
        List<Integer> alarmStatusList = new ArrayList<>();
        if (alarmStatus == 0) {
            alarmStatusList.addAll(Arrays.asList(1,2,3,4));
        } else {
            alarmStatusList.add(alarmStatus);
        }

        return alarmStatusList;
    }
    @Override
    @Transactional
    public void editTemplate(RunningReportTemplateRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        RunningReportTemplateResponse response = templateDetail(false);
        log.info("runningReportTemplateResponse:{}", response);
        // 查询运行报告配置信息是否存在
        QueryWrapper<RunningReportConfig> runningReportConfigWrapper = new QueryWrapper<>();
        runningReportConfigWrapper.lambda().eq(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(RunningReportConfig::getSpId, spId);
        RunningReportConfig runningReportConfig = this.getOne(runningReportConfigWrapper);
        if (runningReportConfig == null) {
            runningReportConfig = new RunningReportConfig();
            //设置默认的运行报告配置
            runningReportConfig.setGenerateReportOpen(OpenCloseEnum.CLOSE.getCode());
            runningReportConfig.setGenerateReportDay(2);
            Map<String, String> checkOpenMap = new HashMap<>();
            List<String> custTypes = consumerMapper.selectUserType(spId);
            if (CollectionUtils.isNotEmpty(custTypes)) {
                for (String type : custTypes) {
                    if (StringUtils.isNotEmpty(type)) {
                        checkOpenMap.put(type, OpenCloseEnum.OPEN.getCode());
                    }
                }
                // 未知，其他
                if (consumerMapper.selectUserTypeCount(spId, "其他") > 0) {
                    checkOpenMap.put("其他", OpenCloseEnum.OPEN.getCode());
                }
                if (consumerMapper.selectUserTypeCount(spId, "未知") > 0) {
                    checkOpenMap.put("未知", OpenCloseEnum.OPEN.getCode());
                }
                runningReportConfig.setCheckOpen(checkOpenMap == null ? Constants.BLANK : JSON.toJSONString(checkOpenMap));
            }
        }
        // 删除之前的
        UpdateWrapper<RunningReportConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_FALSE)
            .eq(RunningReportConfig::getSpId, spId)
            .set(RunningReportConfig::getIsDeleted, Constants.IS_DELETED_TRUE);
        this.update(updateWrapper);
        BeanUtils.copyProperties(request, runningReportConfig);
        runningReportConfig.setTemplateUpdatedAt(new Date());
        runningReportConfig.setAlarmSummaryListShow(CollectionUtils.isNotEmpty(request.getAlarmSummaryList()) ? JSON.toJSONString(request.getAlarmSummaryList()) : "");
        runningReportConfig.setAlarmDetailListShow(CollectionUtils.isNotEmpty(request.getAlarmDetailList()) ? JSON.toJSONString(request.getAlarmDetailList()) : "");
        runningReportConfig.setSpId(spId);
        this.save(runningReportConfig);
        //企业级操作日志
        LogVO vo = new LogVO();
        StringBuilder stringBuilder = new StringBuilder();
        if (!response.getHeaderShow().equals(runningReportConfig.getHeaderShow())) {
            stringBuilder.append("基础设置：页眉内容由【").append(ShowAndSelectEnum.getValue(response.getHeaderShow()).getName()).append("】变更成【").append(ShowAndSelectEnum.getValue(runningReportConfig.getHeaderShow()).getName()).append("】\n");
        }
        StringBuilder headerDetail = new StringBuilder();
        if (StringUtils.isNotEmpty(runningReportConfig.getHeaderLogo()) && !response.getHeaderLogo().equals(runningReportConfig.getHeaderLogo())) {
            headerDetail.append("Logo图片调整，");
        }
        if (StringUtils.isNotEmpty(runningReportConfig.getHeaderContent()) && !response.getHeaderContent().equals(runningReportConfig.getHeaderContent())) {
            headerDetail.append("内容修改，");
        }
        if (request.getHeaderRestoreDefault() != null && request.getHeaderRestoreDefault()) {
            headerDetail.append("恢复默认，");
        }
        if (headerDetail.length() > 0) {
            stringBuilder.append("基础设置：页眉内容，").append(headerDetail.deleteCharAt(headerDetail.length() - 1)).append("\n");
        }
        // 报告说明（无报警）
        StringBuilder noAlarmDetail = new StringBuilder();
        if (StringUtils.isNotEmpty(runningReportConfig.getNoAlarmContent()) && !response.getNoAlarmContent().equals(runningReportConfig.getNoAlarmContent())) {
            noAlarmDetail.append("内容修改，");
        }
        if (runningReportConfig.getNoAlarmTipsShow() != null && response.getNoAlarmTipsShow() != runningReportConfig.getNoAlarmTipsShow()) {
            noAlarmDetail.append("温馨提示由【").append(ShowAndSelectEnum.getValue(response.getNoAlarmTipsShow()).getValue()).append("】变更成【").append(ShowAndSelectEnum.getValue(runningReportConfig.getNoAlarmTipsShow()).getValue()).append("】,");
        }
        if (request.getNoAlarmRestoreDefault() != null && request.getNoAlarmRestoreDefault()) {
            noAlarmDetail.append("恢复默认，");
        }
        if (noAlarmDetail.length() > 0) {
            stringBuilder.append("报告说明（无报警）：").append(noAlarmDetail.deleteCharAt(noAlarmDetail.length() - 1)).append("\n");
        }
        // 报告说明（有报警）-报警总结
        StringBuilder alarmSummaryDetail = new StringBuilder();
        if (runningReportConfig.getIsAlarmSummary() != null && response.getIsAlarmSummary() != runningReportConfig.getIsAlarmSummary()) {
            alarmSummaryDetail.append("由【").append(ShowAndSelectEnum.getValue(response.getIsAlarmSummary()).getName()).append("】变更成【").append(ShowAndSelectEnum.getValue(runningReportConfig.getIsAlarmSummary()).getName()).append("】,");
        }
        if (StringUtils.isNotEmpty(runningReportConfig.getAlarmSummaryContent()) && !response.getAlarmSummaryContent().equals(runningReportConfig.getAlarmSummaryContent())) {
            alarmSummaryDetail.append("内容修改，");
        }
        if (StringUtils.isNotEmpty(runningReportConfig.getAlarmSummaryTitle()) && !response.getAlarmSummaryTitle().equals(runningReportConfig.getAlarmSummaryTitle())) {
            alarmSummaryDetail.append("燃气报警监控记录报告标题修改，");
        }
        if (CollectionUtils.isNotEmpty(request.getAlarmSummaryList()) && CollectionUtils.isNotEmpty(response.getAlarmSummaryList()) && !JSON.toJSONString(request.getAlarmSummaryList()).equals(JSON.toJSONString(response.getAlarmSummaryList()))) {
            alarmSummaryDetail.append("燃气报警监控记录报告字段修改，");
        }
        List<String> alarmSummarySelectList = new ArrayList<>();
        List<String> alarmSummaryDeselectList = new ArrayList<>();
        if (runningReportConfig.getCategoryAnalysisShow() != null && response.getCategoryAnalysisShow() != runningReportConfig.getCategoryAnalysisShow()) {
            if (runningReportConfig.getCategoryAnalysisShow() == ShowAndSelectEnum.SHOW.getCode()) {
                alarmSummarySelectList.add("事件分析");
            } else {
                alarmSummaryDeselectList.add("事件分析");
            }
        }
        if (runningReportConfig.getSituationAnalysisShow() != null && response.getSituationAnalysisShow() != runningReportConfig.getSituationAnalysisShow()) {
            if (runningReportConfig.getSituationAnalysisShow() == ShowAndSelectEnum.SHOW.getCode()) {
                alarmSummarySelectList.add("事件原因分析");
            } else {
                alarmSummaryDeselectList.add("事件原因分析");
            }
        }
        if (CollectionUtils.isNotEmpty(alarmSummarySelectList)) {
            alarmSummaryDetail.append("报警情况图示选择");
            alarmSummarySelectList.forEach(x -> {
                alarmSummaryDetail.append("【").append(x).append("】");
            });
            alarmSummaryDetail.append(Constants.CHINESE_SPLITOR);
        }
        if (CollectionUtils.isNotEmpty(alarmSummaryDeselectList)) {
            alarmSummaryDetail.append("报警情况图示取消选择");
            alarmSummaryDeselectList.forEach(x -> {
                alarmSummaryDetail.append("【").append(x).append("】");
            });
            alarmSummaryDetail.append(Constants.CHINESE_SPLITOR);
        }
        if (request.getAlarmSummaryRestoreDefault() != null && request.getAlarmSummaryRestoreDefault()) {
            alarmSummaryDetail.append("恢复默认，");
        }
        if (alarmSummaryDetail.length() > 0) {
            stringBuilder.append("报告说明（有报警）-报警总结：").append(alarmSummaryDetail.deleteCharAt(alarmSummaryDetail.length() - 1)).append("\n");
        }
        // 报告说明（有报警）-报警明细
        StringBuilder alarmDetailDetail = new StringBuilder();
        if (runningReportConfig.getIsAlarmDetail() != null && response.getIsAlarmDetail() != runningReportConfig.getIsAlarmDetail()) {
            alarmDetailDetail.append("由【").append(ShowAndSelectEnum.getValue(response.getIsAlarmDetail()).getName()).append("】变更成【").append(ShowAndSelectEnum.getValue(runningReportConfig.getIsAlarmDetail()).getName()).append("】,");
        }
        if (StringUtils.isNotEmpty(runningReportConfig.getAlarmDetailTitle()) && !response.getAlarmDetailTitle().equals(runningReportConfig.getAlarmDetailTitle())) {
            alarmSummaryDetail.append("燃气报警记录明细表标题修改，");
        }
        List<String> alarmDetailSelectList = new ArrayList<>();
        List<String> alarmDetailDeselectList = new ArrayList<>();
        if (runningReportConfig.getAlarmDetailNameShow() != null && response.getAlarmDetailNameShow() != runningReportConfig.getAlarmDetailNameShow()) {
            if (runningReportConfig.getAlarmDetailNameShow() == ShowAndSelectEnum.SHOW.getCode()) {
                alarmDetailSelectList.add("户名");
            } else {
                alarmDetailDeselectList.add("户名");
            }
        }
        if (runningReportConfig.getAlarmDetailCodeShow() != null && response.getAlarmDetailCodeShow() != runningReportConfig.getAlarmDetailCodeShow()) {
            if (runningReportConfig.getAlarmDetailCodeShow() == ShowAndSelectEnum.SHOW.getCode()) {
                alarmDetailSelectList.add("户号");
            } else {
                alarmDetailDeselectList.add("户号");
            }
        }
        if (runningReportConfig.getAlarmDetailAddressShow() != null && response.getAlarmDetailAddressShow() != runningReportConfig.getAlarmDetailAddressShow()) {
            if (runningReportConfig.getAlarmDetailAddressShow() == ShowAndSelectEnum.SHOW.getCode()) {
                alarmDetailSelectList.add("户址");
            } else {
                alarmDetailDeselectList.add("户址");
            }
        }
        if (CollectionUtils.isNotEmpty(alarmDetailSelectList)) {
            alarmSummaryDetail.append("客户信息展示选择");
            alarmDetailSelectList.forEach(x -> {
                alarmSummaryDetail.append("【").append(x).append("】");
            });
            alarmSummaryDetail.append(Constants.CHINESE_SPLITOR);
        }
        if (CollectionUtils.isNotEmpty(alarmDetailDeselectList)) {
            alarmSummaryDetail.append("客户信息展示取消选择");
            alarmDetailDeselectList.forEach(x -> {
                alarmSummaryDetail.append("【").append(x).append("】");
            });
            alarmSummaryDetail.append(Constants.CHINESE_SPLITOR);
        }
        if (CollectionUtils.isNotEmpty(request.getAlarmDetailList()) && CollectionUtils.isNotEmpty(response.getAlarmDetailList()) && !JSON.toJSONString(request.getAlarmDetailList()).equals(JSON.toJSONString(response.getAlarmDetailList()))) {
            alarmSummaryDetail.append("燃气报警记录明细表字段修改，");
        }
        if (request.getAlarmDetailRestoreDefault() != null && request.getAlarmDetailRestoreDefault()) {
            alarmDetailDetail.append("恢复默认，");
        }
        if (alarmDetailDetail.length() > 0) {
            stringBuilder.append("报告说明（有报警）-报警明细：").append(alarmDetailDetail.deleteCharAt(alarmDetailDetail.length() - 1)).append("\n");
        }
        // 报告说明（有报警）-温馨提示
        StringBuilder tipsDetail = new StringBuilder();
        if (runningReportConfig.getIsTips() != null && response.getIsTips() != runningReportConfig.getIsTips()) {
            tipsDetail.append("由【").append(ShowAndSelectEnum.getValue(response.getIsTips()).getName()).append("】变更成【").append(ShowAndSelectEnum.getValue(runningReportConfig.getIsTips()).getName()).append("】,");
        }
        if (StringUtils.isNotEmpty(runningReportConfig.getTipsContent()) && !response.getTipsContent().equals(runningReportConfig.getTipsContent())) {
            tipsDetail.append("内容修改，");
        }
        if (runningReportConfig.getTipsShow() != null && response.getTipsShow() != runningReportConfig.getTipsShow()) {
            tipsDetail.append("温馨提示由【").append(ShowAndSelectEnum.getValue(response.getTipsShow()).getValue()).append("】变更成【").append(ShowAndSelectEnum.getValue(runningReportConfig.getTipsShow()).getValue()).append("】");
        }
        if (request.getTipsRestoreDefault() != null && request.getTipsRestoreDefault()) {
            tipsDetail.append("恢复默认，");
        }
        if (tipsDetail.length() > 0) {
            stringBuilder.append("报告说明（有报警）-温馨提示：").append(tipsDetail.deleteCharAt(tipsDetail.length() - 1));
        }

        vo.setDetail(stringBuilder.toString());
        log.info("LogVO-vo:{}", JSONObject.toJSONString(vo));
        LogRecordAspect.threadLocal.set(vo);

    }

}
